<template>
    <Page>
        <Topbar active="首页" />
        <Content>
            <Panel header :title="`设备编号：${device.deviceNo}`" style="padding: 5rem;">
                <view class="row">
                    <view class="column column1">
                        <view class="chart">
                            <EChartBar ref="eChartBar"></EChartBar>
                        </view>
                        <view class="text">
                            设备利用率
                        </view>
                    </view>
                    <view class="column" style="width: 28%;">
                        <view class="form-item">
                            <view class="label">
                                生产工单:
                            </view>
                            <view class="text">
                                {{ data.workCode || '--' }}
                            </view>
                        </view>
                        <view class="form-item">
                            <view class="label">
                                产品型号:
                            </view>
                            <view class="text">
                                {{ data.materialType || '--' }}
                            </view>
                        </view>
                        <view class="form-item">
                            <view class="label">
                                产品编号:
                            </view>
                            <view class="text">
                                {{ data.materialCode || '--' }}
                            </view>
                        </view>
                        <view class="form-item">
                            <view class="label">
                                计划/合格/欠数:
                            </view>
                            <view class="text">
                                {{ data.planProduceQuantity || '--' }}/{{ data.reportedQuantity || '--' }}/{{ getLackofProduceQuantity(data) }}
                            </view>
                        </view>
                        <view class="form-item">
                            <view class="label">
                                模具编号:
                            </view>
                            <view class="text">
                                {{ data.moldCode || '--' }}
                            </view>
                        </view>
                        <view class="form-item">
                            <view class="label">
                                预计完工时间:
                            </view>
                            <view class="text">
                                {{ data.predictComplateTime || getPredictComplateTime(data) }}
                            </view>
                        </view>
                    </view>
                    <view class="column" style="width: 28%;position: relative;left: -3rem;">
                        <view class="form-item">
                            <view class="label">
                                产品名称:
                            </view>
                            <view class="text">
                                {{ data.materialName || '--' }}
                            </view>
                        </view>
                        <view class="form-item">
                            <view class="label">
                                标准/实际腔型数:
                            </view>
                            <view class="text">
                                {{ data.cavityNum || '--' }}/{{ data.realityCavityNum || '--' }}
                            </view>
                        </view>
                        <view class="form-item">
                            <view class="label">
                                标准/实际周期:
                            </view>
                            <view class="text">
                                {{ data.moldingCycle || '--' }}/{{ data.actualPeriod || '--' }}
                            </view>
                        </view>
                        <view class="form-item">
                            <view class="label">
                                模具名称:
                            </view>
                            <view class="text">
                                {{ data.moldName || '--' }}
                            </view>
                        </view>
                        <view class="form-item">
                            <view class="label">
                                报工数量:
                            </view>
                            <view class="text">
                                {{ data.reportedNum || 0 }}
                            </view>
                        </view>
                        <view class="form-item">
                            <view class="label">
                                生产进度:
                            </view>
                            <view class="text">
                                <view class="progress">
                                    <view class="per" :style="{ width: getProcessNum(data) +'%' }" />
                                    <view class="val">
                                        {{ getProcessNum(data) +'%'}}
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class="column column4">
                        <view class="status-panel">
                            <view class="title">
                                设备状态
                            </view>
                            <view class="icon">
                                <image mode="aspectFit" :src="ICON_START" />
                            </view>
                            <view
                                :class="['text', {'text-c1': data.stateName === '运行' }, {'text-c2': data.stateName === '待机' }, {'text-c3': data.stateName === '停机' }]">
                                {{ data.stateName }}
                            </view>
                        </view>
                        <view class="status-panel" style="margin-top: 2rem;">
                            <view class="title">
                                工单状态
                            </view>
                            <view class="icon">
                                <image mode="aspectFit" :src="ICON_SETTING" />
                            </view>
                            <view class="text text-c4">
                                {{ data.workState || '无工单' }}
                            </view>
                        </view>
                    </view>
                </view>
            </Panel>
            <Panel header column :title="`设备运行状态(${dayjs().format('YYYY-MM-DD')})`" style="padding: 5rem;">
                <view slot="toolbar">
                    <view class="state-group">
                        <view class="state-item">
                            <view class="color" style="background-color: #50a47a"></view>
                            <view class="text" style="margin-left: 1rem;">
                                设备运行
                            </view>
                        </view>
                        <view class="state-item" style="margin-left: 3rem;">
                            <view class="color" style="background-color: #e9ac4b;"></view>
                            <view class="text" style="margin-left: 1rem;">
                                设备待机
                            </view>
                        </view>
                        <view class="state-item" style="margin-left: 3rem;">
                            <view class="color" style="background-color: #ee795d;"></view>
                            <view class="text" style="margin-left: 1rem;">
                                设备停机
                            </view>
                        </view>
                    </view>
                </view>
                <view class="state-line">
                    <view class="header">
                        <view class="title">
                            {{ device.deviceNo }}
                        </view>
                    </view>
                    <view class="body">
                        <view :class="['line-part', 'line-part-' + item.state, 'line-part-index' + index]"
                            v-for="(item, index) in stateLine" :key="index" :style="{
                            width: item.value / stateTotal * 100 + '%'
                        }" :ref="`line-part-${index}`" @touchstart="onTouchStart($event, item, index)"
                            @touchend="onTouchEnd">
                        </view>
                    </view>
                    <view class="footer">
                        <view class="time" v-for="(item, index) in timeLine" :key="index">
                            {{ item }}
                        </view>
                    </view>
                </view>
                <view class="schedule" v-for="(table, tableIndex) in schedule" :key="tableIndex">
                    <table>
                        <thead>
                            <tr>
                                <th>{{table.className}}</th>
                                <th v-for="(item, index) in table.classHourRate" :key="index">{{item.timeQuantum}}</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>目标产出</td>
                                <td v-for="item in table.classHourRate">{{item.targetOutput}}</td>
                            </tr>
                            <tr>
                                <td>实际生产</td>
                                <td v-for="item in table.classHourRate">{{item.actulOutput}}</td>
                            </tr>
                            <tr>
                                <td>报废数量</td>
                                <td v-for="item in table.classHourRate">{{item.scrapCount}}</td>
                            </tr>
                            <tr>
                                <td>合格率</td>
                                <td v-for="item in table.classHourRate">{{(item.qualifiedRate).toFixed(0) + '%'}}
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </view>
            </Panel>
        </Content>
        <!-- PAD TIPS -->
        <Tooltip ref="tooltip">
            <view style="border-bottom: 1px solid #eee; margin-bottom: 2rem; padding-bottom: 1rem; font-weight: bold;">
                {{ activeLine.stateName ? activeLine.stateName : '其他' }}
            </view>
            <view class="body">
                <view class="row">
                    开始时间：{{ activeLine.startDateTime }}
                </view>
                <view class="row" style="margin-top: 1rem;">
                    结束时间：{{ activeLine.endDateTime }}
                </view>
            </view>
        </Tooltip>
    </Page>
</template>

<script>
    import Page from "@/components/page/index.vue";
    import Topbar from "@/components/topbar/index.vue";
    import Content from "@/components/content/index.vue";
    import Panel from "@/components/panel/index.vue";
    import Tooltip from "@/components/tooltip/index.vue";
    import filter from "@/utils/filter";
    import fetch from "@/utils/fetch";
    import EChartBar from "./chart/bar.vue";
    import ICON_START from './img/icon-start.png';
    import ICON_SETTING from './img/icon-setting.png';
    import {
        setMenu,
        getDevice
    } from '@/store/user.js';

    export default {
        components: {
            Page,
            Topbar,
            Content,
            Panel,
            Tooltip,
            EChartBar,
        },
        data() {
            return {
                activeLine: {},
                data: {},
                filter,
                ICON_START,
                ICON_SETTING,
                stateTotal: 0,
                stateLine: [],
                timeLine: [],
                schedule: [],
                device: {}
            };
        },
        methods: {
            //欠数：计划减去合格 要大于零
            getLackofProduceQuantity(data) {
                if (data.planProduceQuantity && data.reportedQuantity) {
                    const num = data.planProduceQuantity - data.reportedQuantity;
                    return num >= 0 ? num : 0;
                } else {
                    return '--';
                }
            },
            //当前时间+（剩余数量【欠数】*理论节拍/实际型腔数）
            getPredictComplateTime(data) {
                if (!data.planProduceQuantity || !data.reportedQuantity || !data.moldingCycle || !data
                    .realityCavityNum) {
                    return '--';
                }
                const p1 = data.planProduceQuantity - data.reportedQuantity;
                const p2 = data.moldingCycle;
                const p3 = data.realityCavityNum;
                const millisecond = p1 * p3 / p3 * 1000;
                const now = Number(new Date());
                return this.dayjs(new Date(now + millisecond)).format('YYYY-MM-DD hh:mm:ss');
            },
            getProcessNum(data) {
                if (!data.reportedQuantity || !data.planProduceQuantity) {
                    return 0;
                }
                return (data.reportedQuantity / data.planProduceQuantity * 100).toFixed(2)
				// if (!data.planProduceQuantity || !data.realityCavityNum || !data.scrapQuantity) {
				//    return 0;
				// }
				// return ((data.produceQuantity * data.realityCavityNum * data.scrapQuantity) / data.planProduceQuantity *
                //         100)
                //     .toFixed(2)
            },
            onTouchStart(e, item, index) {
                this.activeLine = item;
                uni.createSelectorQuery().select('.line-part-index' + index).boundingClientRect((res) => {
                    this.$refs['tooltip'].open(e.currentTarget.offsetLeft + (res.width / 2), e
                        .currentTarget.offsetTop + 5);
                }).exec();
            },
            onTouchEnd() {
                this.$refs['tooltip'].close();
            },
            setLine(list) {
                if (list.length !== 0) {
                    this.timeLine = [];
                    const startDateTime = new Date(list[0].startDateTime)
                    const endDateTime = new Date(list[list.length - 1].endDateTime)
                    this.stateTotal = Number(endDateTime) - Number(startDateTime);
                    const startDay = startDateTime.getDate();
                    const endDay = endDateTime.getDate();
                    const startHour = startDateTime.getHours();
                    let endHour;
                    if (endDay - startDay > 0) {
                        endHour = endDateTime.getHours() + (endDay - startDay) * 24;
                    } else {
                        endHour = endDateTime.getHours() + 24;
                    }
                    for (let i = 0; i < endHour - startHour + 1; i++) {
                        let hour = i + startHour;
                        if (hour > 23) {
                            hour -= 24;
                        }
                        this.timeLine.push(hour < 10 ? '0' + hour + ':00' : hour + ':00');
                    }
                } else {
                    this.timeLine = ['00:00', '00:24'];
                }
            },
            setEchart(refName, name, data) {
                const obj = {
                    title: {
                        name: data + "%",
                        fontSize: '32',
                        color: "#000",
                    },
                };
                let res = {
                    series: [{
                        name: name,
                        color: "#83b6f3",
                        data: data / 100,
                    }],
                };
                this.$refs[refName].init(obj);
                this.$refs[refName].setData(res);
            },
            getData() {
                this.device = getDevice();
                fetch('get', '/dms/mobile/production/first', {
                    deviceId: this.device.id
                }).then((res) => {
                    this.data = res;
                    this.$nextTick(() => {
                        this.setEchart('eChartBar', '设备利用率', res.deviceUseRatio);
                    });
                });
                fetch('get', '/dms/mobile/state/diagram', {
                    deviceId: this.device.id
                }).then((res) => {
                    this.stateLine = (res || [{
                        stateName: '',
                        startDateTime: dayjs().format('YYYY-MM-DD') + '00:00:00',
                        endDateTime: dayjs().format('YYYY-MM-DD') + '24:00:00',
                    }]).map((item) => {
                        return {
                            value: Number(new Date(item.endDateTime)) - Number(new Date(item
                                .startDateTime)),
                            state: this.convertState(item.stateName),
                            stateName: item.stateName,
                            startDateTime: item.startDateTime,
                            endDateTime: item.endDateTime
                        }
                    });
                    this.setLine(this.stateLine);
                });
                fetch('get', '/dms/mobile/class/qualifiedRate', {
                    deviceId: this.device.id
                }).then((res) => {
                    this.schedule = res || [];
                });
            },
            convertState(stateName) {
                switch (stateName) {
                    case '运行':
                        return 1;
                    case '待机':
                        return 2;
                    case '停机':
                        return 3;
                    default:
                        return 4;
                }
            }
        },
        onShow() {
            fetch('get', '/basic/menu/findPermissionByToken').then(res => {
                setMenu(res)
            });
            if (getDevice()) {
                this.getData();
            } else {
                uni.navigateTo({
                    url: '/pages/device/index'
                });
            }
        },
    };
</script>

<style scoped lang="scss">
    .row {
        flex: 1;
        display: flex;
        justify-content: space-between;
    }

    .column1 {
        width: 15%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        .chart {
            width: 80%;
            height: 30rem;
        }

        .text {
            color: #999;
        }
    }

    .column4 {
        width: 20%;
        display: flex;
        flex-direction: column;
    }

    .progress {
        position: relative;
        height: 2rem;
        flex: 1;
        background: #f0f1f3;
        border-radius: 2rem;
        overflow: hidden;
        display: flex;
        justify-content: center;
        align-items: center;

        .per {
            position: absolute;
            top: 0;
            left: 0;
            background: #66bb6a;
            height: 100%;
            border-radius: 2rem;
        }

        .val {
            position: relative;
        }
    }

    .form-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 0 0 3rem;

        .label {
            color: #999;
            flex: 1;
            display: flex;
            justify-content: flex-end;
        }

        .text {
            color: #333;
            width: 28rem;
            word-break: break-all;
            margin-left: 4rem;
        }

        &:last-child {
            margin-bottom: 0;
        }
    }

    .status-panel {
        flex: 1;
        position: relative;
        background: #f5f7fa;
        border-radius: 1rem;

        .title {
            position: absolute;
            top: 2rem;
            left: 2rem;
        }

        .icon {
            position: absolute;
            bottom: 1rem;
            left: 1rem;
            width: 5rem;
            height: 5rem;
            display: flex;
        }

        .text {
            position: absolute;
            bottom: 2rem;
            right: 2rem;

            &-c1 {
                color: #79c27d;
            }

            &-c2 {
                color: #e9ac4b;
            }

            &-c3 {
                color: #ee795d;
            }

            &-c4 {
                color: #4bacdc;
            }
        }
    }

    .state-group {
        display: flex;
        align-items: center;

        .state-item {
            display: flex;
            align-items: center;

            .color {
                width: 1.5rem;
                height: 1.5rem;
                border-radius: 1rem;
            }
        }
    }

    .state-line {
        display: flex;
        flex-direction: column;
        align-items: center;
        background-color: #fafbfd;
        padding: 3rem;
        border-radius: 1rem;

        .header {
            display: flex;
            flex-direction: column;
            width: 100%;

            .title {
                font-weight: bold;
                margin-bottom: 2rem;
            }
        }

        .body {
            height: 2rem;
            overflow: hidden;
            border-radius: 2rem;
            width: 100%;
            display: flex;

            .line-part {
                height: 100%;

                &-1 {
                    background-color: #50a47a;
                }

                &-2 {
                    background-color: #e9ac4b;
                }

                &-3 {
                    background-color: #ee795d;
                }

                &-4 {
                    background-color: #eee;
                }
            }
        }

        .footer {
            margin-top: 1rem;
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

    }

    .schedule {
        margin-top: 3rem;
        width: 100%;

        table {
            width: 100%;
            background: #fafbfd;
            border: 1px solid transparent;

            th {
                height: 4rem;
                line-height: 4rem;
                text-align: center;
                background-color: #fafbfd;
            }

            td {
                height: 4rem;
                line-height: 4rem;
                text-align: center;
                background-color: #ffffff;
            }
        }
    }
</style>